package com.manager.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.manager.pojo.TbUser;
import com.manager.service.UserService;
import com.manager.vo.TbUserEx;


//import cn.itcast.vcode.utils.VerifyCode;

/**
 * 
 * @Title:  LoginControl.java     
 * @Description:    登入Controller
 * @author:      
 * @date:   2019年2月13日 上午10:52:07   
 * @version V1.0
 */
@Controller
public class LoginControl {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/login")
	public String login() {
		
		return "login";
	}
	
	@RequestMapping("/VerifyCode")
	public void verifyCode(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
		
		// 创建一个宽100,高50,且不带透明色的image对象 100 50
        BufferedImage bi = new BufferedImage(85, 40, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        //RGB色彩
        Color c = new Color(200, 150, 255);
        // 框中的背景色
        g.setColor(c);
        // 颜色填充像素
        g.fillRect(0, 0, 100, 50);

        // 定义验证码字符数组
        char[] ch = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456798".toCharArray();
        
        Random r = new Random();
        int len = ch.length;
        int index;
        
        StringBuffer sb = new StringBuffer();
        
        // 取出四个数字
        for (int i = 0; i < 4; i++) {
            // 循环四次随机取长度定义为索引
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            Font font = new Font("Times New Roman", Font.ITALIC, 18);
            g.setFont(font);
            g.drawString(ch[index] + "", (i * 18) + 10, 30);
            sb.append(ch[index]);
        }
        
        //放入Session中
        session.setAttribute("piccode", sb.toString());
        System.out.println(sb.toString());
        
        try {
            ImageIO.write(bi, "JPG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

	}
	
	//处理登入请求
	@RequestMapping("/logins")
	public String logins(TbUser tbUser,String yanma,HttpSession session,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		if(tbUser.getUsername().isEmpty()) {
			
			tbUserEx.setCode(400);
			tbUserEx.setError("用户名不能为空");
			model.addAttribute("tbUserEx", tbUserEx);
			return "error";
		}
		
		if(tbUser.getPassword().isEmpty()) {
			
			tbUserEx.setCode(400);
			tbUserEx.setError("密码不能为空");
			model.addAttribute("tbUserEx", tbUserEx);
			return "error";
		}else {
			
			if(tbUser.getPassword().length()<6) {
				tbUserEx.setCode(400);
				tbUserEx.setError("密码长度不能小于6位");
				model.addAttribute("tbUserEx", tbUserEx);
				return "error";
			}
		}
		
		if(yanma.isEmpty()) {
			
			tbUserEx.setCode(400);
			tbUserEx.setError("验证码不能为空");
			model.addAttribute("tbUserEx", tbUserEx);
			return "error";
			
		}else {
			
			if(yanma.length() != 4) {
				tbUserEx.setCode(400);
				tbUserEx.setError("验证码位数不对");
				model.addAttribute("tbUserEx", tbUserEx);
				return "error";
			}
			 
		}
		
		//Session中存好的验证码数值
		String piccode = (String) session.getAttribute("piccode");
		
		// 验证码判断
		if (!yanma.equalsIgnoreCase(piccode)) {
			tbUserEx.setCode(400);
			tbUserEx.setError("验证码不正确");
			model.addAttribute("tbUserEx", tbUserEx);
			return "error";
		}
		
		try {
			tbUserEx = userService.getUserByUsernameAndPassword(tbUser);
		}catch(Exception e) {
			
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("登入异常");
			model.addAttribute("tbUserEx", tbUserEx);
			return "error";
		}
	
		if(tbUserEx.getCode()==200) {
			session.setAttribute("user", tbUserEx.getRows().get(0));
			System.out.println("用户加入session了");
		}else {
			model.addAttribute("tbUserEx", tbUserEx);
			return "error";
		}
		
		return "index";
	}
	
	//登出
	@RequestMapping("/loginout")
	public String loginout(HttpSession session) {
		
		session.removeAttribute("user");
		System.out.println("session清除了");
		
		//页面重定向到登入
		return "redirect:login";
	}
	
	
}
